from _datetime import datetime
from flask import Flask,render_template,flash
from flask_mongoengine import MongoEngine

app = Flask(__name__)

'''
  配置连接
'''
app.config['MONGODB_SETTINGS'] = {
    'db': 'flask_news',
    'host': '127.0.0.1',
    'port': 27017
}

db = MongoEngine(app)

NEWS_TYPES =(
    ('推荐', '推荐'),
    ('百家', '百家'),
    ('本地', '本地'),
    ('图片', '图片')
)

'''定义新闻模型'''
class News(db.Document):
    title =   db.StringField(required=True, max_length=200)
    img_url = db.StringField()
    content = db.StringField()
    is_valid = db.BooleanField(default=True)
    created_at = db.DateTimeField(default=datetime.now())
    updated_at = db.DateTimeField(default=datetime.now())
    news_type = db.StringField(required=True, choices=NEWS_TYPES)

    meta = {
        'collection': 'news',
        'ordering': ['-created_at']  #排序
    }

    def __repr__(self):
        return '<News %r>' % self.title


@app.route('/hello')
def hello():
    return 'Hello Flask'

@app.route('/')
def index():
    """ 新闻首页 """
    news_list = News.objects.filter(is_valid=True)
    print(news_list.count)
    return render_template("index.html", news_list=news_list)

@app.route('/cat/<name>/')
def cat(name):
    """ 新闻类别页面 """
    news_list = News.objects.filter(is_valid=True, news_type=name)
    return render_template('cat.html', name=name, news_list=news_list)


@app.route('/detail/<pk>/')
def detail(pk):
    """ 新闻详情页 """
    new_obj = News.objects.filter(pk=pk).first()
    return render_template('detail.html', new_obj=new_obj)

if __name__ == '__main__':
    app.run(debug=True)
